package cn.wolfcode.mongo.service.impl;

import cn.wolfcode.entity.Userinfo;
import cn.wolfcode.mongo.domain.StrategyComment;
import cn.wolfcode.mongo.query.StrategyCommentQuery;
import cn.wolfcode.mongo.repository.StrategyCommentRepository;
import cn.wolfcode.mongo.service.IStrategyCommentMongoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IStrategyCommentMongoServiceImpl implements IStrategyCommentMongoService {
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(StrategyComment comment, Userinfo user) {
        BeanUtils.copyProperties(user, comment);
        comment.setUserId(user.getId());
        comment.setId(null);
        comment.setCreateTime(new Date());
        strategyCommentRepository.save(comment);
    }

    @Override
    public Page queryPage(StrategyCommentQuery qo) {
        Query query = new Query();
        if (qo.getStrategyId() != null) {
            Criteria criteria = Criteria.where("strategyId").is(qo.getStrategyId());
            query.addCriteria(criteria);
        }
        long count = mongoTemplate.count(query, StrategyComment.class);

        if (count <= 0) {
            return Page.empty();
        }
        // 分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        List<StrategyComment> strategyComments = mongoTemplate.find(query, StrategyComment.class);
//        query.skip((long) (qo.getCurrentPage() - 1) * qo.getPageSize()).limit(qo.getPageSize());
        PageImpl<StrategyComment> res = new PageImpl<StrategyComment>(strategyComments);
        return res;

    }
}
